<?php
/**
 * Created by PhpStorm.
 * User: Zhanghaiqiang
 * Date: 2020-03-08
 * Time: 22:47
 */

namespace App\Core\Endpoints\CandyStory;


use Endpoints\Base\Endpoint;
use Endpoints\Tools\GetOssObject;
use Models\Candy\Calendar;
use Models\Candy\Content;
use Models\Candy\Story;
use Symfony\Component\Console\Input\InputArgument;

class IndexStory extends Endpoint
{
// 定义参数
    const ARGUMENT_SEARCH   = 'search';


    // 收参
    public function getArguments()
    {
        return [
            [static::ARGUMENT_SEARCH,InputArgument::OPTIONAL,'搜索项',''],
            [static::ARGUMENT_PAGE,InputArgument::OPTIONAL,'页数',1],
            [static::ARGUMENT_PER_PAGE,InputArgument::OPTIONAL,'获取多少数据','5'],
        ];
    }

    /**
     * 实现逻辑
     * @return \Laravelladder\Core\Collections\BaseCollection
     */
    public function dryRun()
    {
        $search = $this->argument(static::ARGUMENT_SEARCH);
        $page   = $this->argument(static::ARGUMENT_PAGE);
        $limit  = $this->argument(static::ARGUMENT_PER_PAGE);
        $offset = $limit * (($page > 0 ? $page : 1) - 1);

        $list = $this->getCandyStoryRepo()->getListByFilters([],$limit,$offset,['date' => 'desc','id' => 'desc']);

        $list->each(function($item){
            /**
             * @var $item Story
             */
            $imagesCollect = [];
            if($item->{Story::DB_FIELD_STORY_TYPE} == Story::STORY_TYPE_VALUE_IMAGES_COLLECT){
                $imagesCollect = IndexStoryImages::getInstance()->setArguments([IndexStoryImages::ARGUMENT_STORY_ID=>$item->getKey()])->dryRun();
            }
            $item->addFillable('images_collect',$imagesCollect);
            // 处理图片url
            if($item->{Story::DB_FIELD_MEDIA_SOURCE} == Story::MEDIA_SOURCE_ALIYUN){
                $imageUrl = GetOssObject::getInstance()->setArguments([
                    GetOssObject::ARGUMENT_FILE_ID => $item->{Story::DB_FIELD_MEDIA_CONTENT},
                    GetOssObject::ARGUMENT_IMG_OPTION => 'image/resize,m_lift,h_500,w_500',
                ])->dryRun();
                $item->addFillable('media_url',$imageUrl);
            }else{
                $item->addFillable('media_url',$item->{Story::DB_FIELD_MEDIA_CONTENT});
            }
            // 计算日期,出生默认一天，因此比较填24号
            $diff=date_diff(date_create($item->{Story::DB_FIELD_DATE}),date_create("2019-12-24"));
            $showDate = (($diff->y) ? ($diff->y).'年' : '') .
                (($diff->m) ? ($diff->m).'个月' : '') .
                (($diff->d) ? ($diff->d).'天' : '');
            $item->addFillable('showDate',$showDate);

        });
        return $list;
    }
}